package com.pingao.mp.handle;

import com.pingao.mp.utils.Constant;
import com.pingao.mp.utils.set.MapBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常统一处理
 */
@ControllerAdvice
public class ExceptionHandle {

    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object handle(Exception e) throws IOException {
        LOGGER.error(e.getMessage());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new IOException("获取不到ServletRequestAttributes");
        }
        HttpServletResponse response = attributes.getResponse();
        if (response == null) {
            throw new IOException("获取不到输出流");
        }
        HttpServletRequest request = attributes.getRequest();
        StringBuffer url = request.getRequestURL();
        MapBuilder<String, Object> map = new MapBuilder<>();
        //解决抛出异常，导致不能跨域访问的问题
        if (response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) == null) {
            response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        }
        if (e instanceof MaxUploadSizeExceededException && url.toString().contains("/ckeditor")) {
            map.put("uploaded", 0);
            Map<String, Object> p = new HashMap<>();
            p.put("message", "上传的文件过大，请检查文件大小再次尝试");
            map.put("error", p);
        } else {
            map.put(Constant.ApiMsg, e.getMessage()).put(Constant.ApiStatus, false).put("exception", e.getMessage()).put("login", true);
        }

        if (e instanceof MpException && ((MpException) e).getCode().equals(401)) {
            map.put("login", false);
        }
        return map.get();
    }
}
